package com.neo.tiny.admin.api.user;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neo.tiny.admin.dto.user.UserInfoDTO;
import com.neo.tiny.admin.entity.sys.SysUser;
import com.neo.tiny.admin.entity.sys.SysUserPost;
import com.neo.tiny.admin.service.sys.SysUserPostService;
import com.neo.tiny.admin.service.sys.SysUserService;
import com.neo.tiny.common.util.CommonDoTransfer;
import com.neo.tiny.query.LambdaQueryWrapperBase;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: yqz
 * @CreateDate: 2022/10/4 21:12
 */
@Service
@AllArgsConstructor
public class AdminUserApiImpl implements AdminUserApi {
    private final SysUserService userService;

    private final SysUserPostService userPostService;

    @Override
    public void validUsers(Set<Long> ids) {
        userService.validUsers(ids);
    }

    @Override
    public UserInfoDTO getUser(Long userId) {

        SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, userId));
        return CommonDoTransfer.transfer(sysUser, UserInfoDTO.class);
    }

    @Override
    public List<UserInfoDTO> getUsers(Collection<Long> ids) {

        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<SysUser> userList = userService.listByIds(ids);
        return CommonDoTransfer.transfer(userList, UserInfoDTO.class);
    }

    @Override
    public List<UserInfoDTO> getUsersByDeptIds(Collection<Long> deptIds) {
        if (CollUtil.isEmpty(deptIds)) {
            return Collections.emptyList();
        }
        List<SysUser> userList = userService.list(new LambdaQueryWrapperBase<SysUser>()
                .eq(SysUser::getDeptId, deptIds));

        return CommonDoTransfer.transfer(userList, UserInfoDTO.class);
    }

    @Override
    public List<UserInfoDTO> getUsersByPostIds(Collection<Long> postIds) {

        if (CollUtil.isEmpty(postIds)) {
            return Collections.emptyList();
        }
        List<SysUserPost> userPosts = userPostService.list(new LambdaQueryWrapperBase<SysUserPost>()
                .in(SysUserPost::getPostId, postIds));
        if (CollUtil.isEmpty(userPosts)) {
            return Collections.emptyList();
        }
        Set<Long> userIds = userPosts.stream().map(SysUserPost::getUserId)
                .filter(Objects::nonNull).collect(Collectors.toSet());
        List<SysUser> userList = userService.list(new LambdaQueryWrapperBase<SysUser>()
                .in(SysUser::getId, userIds));

        return CommonDoTransfer.transfer(userList, UserInfoDTO.class);
    }
}
